package com.chuangke.file.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.chuangke.admin.entity.SysDept;
import com.chuangke.admin.entity.SysDict;
import com.chuangke.admin.service.SysDeptService;
import com.chuangke.admin.service.SysDictService;
import com.chuangke.common.exception.ChuangkeException;
import com.chuangke.file.model.FileDbank;
import com.chuangke.file.service.FileCategoryService;
import com.chuangke.file.service.FileDbankService;

@Service
public class FileCategoryServiceImpl implements FileCategoryService {

	@Autowired
	private SysDeptService sysDeptService;
	@Autowired
	private SysDictService sysDictService;
	@Autowired
	private FileDbankService fileDbankService;

	@Override
	public List<SysDict> listCategoryByDbankId(String dbankId) {
		FileDbank dbank = fileDbankService.loadDbankWithSpaceById(dbankId);

		if (!FileDbank.TYPE_DEPT.equals(dbank.getType())) {
			throw new ChuangkeException("暂时只支持企业网盘发布！");
		}
		Map<String, SysDict> dictMap = sysDictService.findMap(SysDict.TYPE_FILE_CATEGORY, dbank.getBelongId());

		return new ArrayList<>(dictMap.values());
	}

	@Override
	public List<Map<String,Object>> listAllCategory() {
		Map<String, SysDict> dictMap = sysDictService.findMap(SysDict.TYPE_FILE_CATEGORY);
		dictMap = dictMap== null ? new HashMap<>() : dictMap ;
		Map<String, List<SysDict>> deptDictMap = dictMap.values().stream()
				.collect(Collectors.groupingBy(SysDict::getDeptId));
		
		List<FileDbank> dbankList = fileDbankService.listDbanks(FileDbank.TYPE_DEPT) ;
		Map<String,FileDbank> dbankMap = dbankList.stream().collect(Collectors.toMap(FileDbank::getBelongId, a -> a));
		
		Map<String, SysDept> deptMap = sysDeptService.findMap();
		List<Map<String,Object>> records = new ArrayList<>() ;
		deptDictMap.keySet().forEach(d->{

            SysDept sysDept = deptMap.get(d) ;
            Map<String, Object> record = new HashMap<>(BeanUtils.beanToMap(sysDept));
			record.put("category", deptDictMap.get(d));
			record.put("dbank", dbankMap.get(d));
			
			records.add(record) ;
		});

		return records;
	}

}
